package com.chen.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.chen.annotation.OptLog;
import com.chen.common.OptTypeConst;
import com.chen.common.Result;
import com.chen.controller.dto.HandPaperDto;
import com.chen.controller.dto.PaperDto;
import com.chen.entity.*;
import com.chen.exception.ServiceException;
import com.chen.mapper.PaperMapper;
import com.chen.mapper.QuestionMapper;
import com.chen.service.IPaperQuestionService;
import com.chen.service.impl.ExamServiceImpl;
import com.chen.service.impl.PaperQuestionServiceImpl;
import com.chen.service.impl.PaperServiceImpl;
import com.chen.service.impl.QuestionServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author personcoder007
 * @since 2022-08-17
 */
@RestController
@RequestMapping("/paper")
@Api(value = "PaperController", tags = "试卷管理")
public class PaperController {


    @Autowired
    private PaperServiceImpl paperService;

    @Resource
    private QuestionServiceImpl questionService;

    @Resource
    private PaperQuestionServiceImpl paperQuestionService;


    @PostMapping("/save")
    @ApiOperation(value = "新增或者更新")
    @OptLog(optType = OptTypeConst.SAVE_OR_UPDATE)
    public Result addDict(@RequestBody Paper paper) {

        paperService.saveOrUpdate(paper);

        return Result.success();
    }

    @PostMapping("/selectAll")
    @ApiOperation(value = "查询所有")
    @OptLog(optType = OptTypeConst.SAVE_OR_UPDATE)
    public Result selectAll() {



        return Result.success(paperService.list());
    }


    //根据id进行删除
    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "删除")
    @OptLog(optType = OptTypeConst.REMOVE)
    public Result deleteDict(@PathVariable("id") int id) {
        paperService.removeById(id);
        return Result.success();
    }

    //批量删除
    @PostMapping("/del/batch")
    @ApiOperation(value = "批量删除")
    @OptLog(optType = OptTypeConst.REMOVE_BATH)
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        paperService.removeByIds(ids);

        return Result.success();
    }


    @RequestMapping("/page")
    @ApiOperation(value = "分页查询")
    public Result selectDict(@RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize,
                             @RequestParam(defaultValue = "") String name) {

        return Result.success(paperService.selectPage(pageNum, pageSize, name));
    }

    @PostMapping("/takePaper")
    @ApiOperation(value = "组卷")
    @OptLog(optType = OptTypeConst.SAVE_OR_UPDATE)
    public Result takePaper(@RequestBody PaperDto paperDto) {

//        删除老的试卷
        Integer paperId = paperDto.getPaperId();
        UpdateWrapper<PaperQuestion> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("paper_id", paperId);
        paperQuestionService.remove(updateWrapper);

        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id", paperDto.getCourseId());

//        根据课程id查出所有改课程的题目
        List<Question> questionList = questionService.list(queryWrapper);
//        选择题
        List<Question> type1List = questionList.stream().filter(question -> question.getType() == 1).collect(Collectors.toList());
//       判断题
        List<Question> type2List = questionList.stream().filter(question -> question.getType() == 2).collect(Collectors.toList());
//     简答题
        List<Question> type3List = questionList.stream().filter(question -> question.getType() == 3).collect(Collectors.toList());
        if (type1List.size() < paperDto.getType1()) {
            throw new ServiceException(-1, "选择题数量不足");
        }
        if (type2List.size() < paperDto.getType2()) {
            throw new ServiceException(-1, "判断题数量不足");
        }
        if (type3List.size() < paperDto.getType3()) {
            throw new ServiceException(-1, "简答题数量不足");
        }

//        开始随机组卷

        List<PaperQuestion> paperQuestionList = getPaperQuestionList(type1List.size(), paperDto.getType1(), type1List, paperDto.getPaperId());
        paperQuestionList.addAll(getPaperQuestionList(type2List.size(), paperDto.getType2(), type2List, paperDto.getPaperId()));
        paperQuestionList.addAll(getPaperQuestionList(type3List.size(), paperDto.getType3(), type3List, paperDto.getPaperId()));

        paperQuestionService.saveBatch(paperQuestionList);
        return Result.success();
    }

    /**
     * 封装一个获取试卷和题目关联关系的list方法
     *
     * @param questionSize      题目总条数
     * @param paperQuestionSize 需要的题目条数
     * @param source            list集合
     * @param paperId           前台传递的paperId
     * @return
     */
    private List<PaperQuestion> getPaperQuestionList(int questionSize, int paperQuestionSize, List<Question> source, Integer paperId) {
        List<Integer> typeRandList = getEleList(questionSize, paperQuestionSize);
        ArrayList<PaperQuestion> list = new ArrayList<>();

        int scoreSum=0;
        for (Integer index : typeRandList) {
            Question question = source.get(index);
            PaperQuestion paperQuestion = new PaperQuestion();
            paperQuestion.setPaperId(paperId);
            paperQuestion.setQuestionId(question.getId());
            list.add(paperQuestion);
        }

        return list;
    }

    /**
     * 随机数
     *
     * @param sourceSize 所有的
     * @param resultSize 取多少
     * @return
     */
    private List<Integer> getEleList(int sourceSize, int resultSize) {
        List<Integer> arrayList = CollUtil.newArrayList();
        for (int i = 0; i < sourceSize; i++) {
            arrayList.add(i);
        }
        return RandomUtil.randomEleList(arrayList, resultSize);
    }


    //批量删除
    @GetMapping("/viewPaper/{paperId}")
    @ApiOperation(value = "查看试卷")
    public Result viewPaper(@PathVariable("paperId") Integer paperId) {
        List<Question> questions = paperQuestionService.selectQuestions(paperId);

        return Result.success(questions);
    }


    @PostMapping("/handPaper")
    @ApiOperation(value = "手动试卷")
    public Result handPaper(@RequestBody HandPaperDto handPaperDto) {
//        删除老的试卷
        Integer paperId = handPaperDto.getPaperId();
        UpdateWrapper<PaperQuestion> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("paper_id", paperId);
        paperQuestionService.remove(updateWrapper);

        if (CollUtil.isEmpty(handPaperDto.getHandlerQuestionIds())) {
            throw new ServiceException(-1, "题目数量不足");
        }

        Integer scoreSum = 0;
        List<Integer> handlerQuestionIds = handPaperDto.getHandlerQuestionIds();
        ArrayList<PaperQuestion> list = new ArrayList<>();
        for (Integer handlerQuestionId : handlerQuestionIds) {
            QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", handlerQuestionId);
            List<Question> questionList = questionService.list(queryWrapper);
            for (Question question : questionList) {
                scoreSum = scoreSum + question.getScore();
            }

            PaperQuestion paperQuestion = new PaperQuestion();
            paperQuestion.setPaperId(handPaperDto.getPaperId());
            paperQuestion.setQuestionId(handlerQuestionId);
            list.add(paperQuestion);
        }
//更新分数
        paperService.update(new UpdateWrapper<Paper>().set("score", scoreSum).eq("id", handPaperDto.getPaperId()));


        paperQuestionService.saveBatch(list);
        return Result.success();
    }


    @GetMapping("/findById/{id}")
    public Result findById(@PathVariable Integer id) {
        return Result.success(paperService.getById(id));


    }
}

